// pages/cuesAdd/index.ts

import { fontSizeCalc, handleCode, handleErrCode } from "../../utils/util";
import { getCuesIndustry } from "../../service/api/api-cues-industry";
import { getApi } from "../../utils/http";
import { saveCuesSubmit } from "../../service/api/api-cues-submit";

const rules = [{
  name: "articleName",
  rule: ["required"],
  msg: ["请输入标题"]
}, {
  name: "articleIndustry",
  rule: ["required"],
  msg: ["请选择行业"]
}, {
  name: "articleContent",
  rule: ["required"],
  msg: ["请输入正文"]
}]

let toast;

Page({

  /**
   * 页面的初始数据
   *
   */
  data: {
    report: {
      articleAttachments: [],// 附件列表
      articleContent: '',// 富文本内容
      articleIndustry: '',// 选中的行业
      articleLabels: [],// 标签
      articleName: '',// 标题
      remarks: '',// 备注
    },// 纪录详情
    access: {} as any,// 当前用户权限
    currentUser: {},// 当前用户信息
    industryList: [],// 可选行业列表
    labelsList: [],// 输入的标签列表
    industryName: '',// 当前选中的行业名
    inputArticleLabels: [],// 输入的labels
    inputArticleContent: '',// 输入的正文
    options: '',

    drawerVisible: false,// 右侧抽屉是否显示
    labelDrawerVisible: false,// 右侧抽屉是否显示
    alertShow: false,// 弹窗提示
    title: '',// 标题
    remarks: '',// 备注
    curLabel: '',// 标签

    topicId: 0,// 选题id
    topicPlanId: 0,// 计划id

    imgArr: [],// 上传的图片列表
    imgIdArr: [],// 上传的图片id列表
    serverUrl: `${getApi()}/cues/attachment/save`,// 服务器url
    imageFormat: ['png', 'jpg', 'JPEG', 'BMP', 'WEBP'],// 支持的文件类型列表

    iconSize: fontSizeCalc(30),
    largeIconSize: fontSizeCalc(40),
    labelSize: fontSizeCalc(32),
    inputSize: fontSizeCalc(32),
    overFontSize: fontSizeCalc(32),
    btnHeight: fontSizeCalc(96) + 'rpx',
    btnLineHeight: fontSizeCalc(70) + 'rpx',
    subLabelSize: fontSizeCalc(26),
    subBtnHeight: fontSizeCalc(60) + 'rpx',
    subBtnLineHeight: fontSizeCalc(24) + 'rpx',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let _that = this;
    const { topicId, topicPlanId } = options || {}
    this.getCuesIndustryFun();
    const { globalData: { access, currentUser }, windowWidth } = getApp();
    let size = windowWidth >= 480 ? 26 : 32;
    this.setData({
      access,
      currentUser,
      topicId,
      topicPlanId,
      options: JSON.stringify(options),
    })
    setTimeout(() => {
      _that.setData({
        inputSize: fontSizeCalc(size),
      })
    }, 500)
  },

  /**
   * 行业列表结构
   */
  async getCuesIndustryFun() {
    let _that = this;
    // 执行搜索函数
    await getCuesIndustry().then(async (res) => {
      if (res?.data) {
        _that.setData({
          industryList: _that.readyData(res.data)
        })
      }
    })
  },

  /**
   * 结构数据
   * @param data
   */
  readyData(data): any {
    let list = [];
    if (Array.isArray(data) && data) {
      list = data.filter(item => item.isDelete === 0).map(item => {
        item.checked = false
        return { ...item }
      })
    }
    return list;
  },

  /**
   * 单选框发生变化
   */
  drawerRadioChange(res: { detail: any }) {
    const id = res.detail?.value;
    const { name } = this.data.industryList.find(item => item.id == id) || {};
    this.setData({
      drawerChannelVisible: false,
      ['report.articleIndustry']: id,
      industryName: name || '',
    })
  },

  /**
   * 显示侧面抽屉
   */
  showDrawer() {
    this.setData({
      drawerVisible: true
    })
  },

  /**
   * 关闭抽屉
   */
  closeDrawer(e) {
    // console.log(e);
    this.setData({
      drawerVisible: false,
    })
  },

  /**
   * 显示侧面抽屉
   */
  showLabelDrawer() {
    this.setData({
      labelDrawerVisible: true
    })
  },

  /**
   * 关闭抽屉
   */
  closeLabelDrawer(e) {
    // console.log(e);
    this.setData({
      labelDrawerVisible: false,
    })
  },

  /**
   * 添加label
   */
  addLabel() {
    const { curLabel, inputArticleLabels } = this.data;
    if (!curLabel && curLabel != '0' || inputArticleLabels.includes(curLabel)) {
      this.setData({
        curLabel: ''
      })
      return
    }
    inputArticleLabels.push(curLabel);
    this.setData({
      inputArticleLabels,
      curLabel: ''
    })
  },

  /**
   * 添加label
   */
  delLabel(e: any) {
    const label = e.currentTarget.dataset.item || {};
    const { inputArticleLabels: labels } = this.data;
    labels.splice(labels.indexOf(label), 1);
    this.setData({
      inputArticleLabels: labels
    })
  },

  /**
   * 图片上传结果
   *
   * status: Number //上传状态 1-成功 2-上传中 3-失败
   * imgArr: Array //图片信息
   * idList: Array //图片id列表
   * params: params //自定义参数
   * manual: false //是否手动上传
   *
   }
   */
  imgUploadResultFun({ detail: { status, imgArr, idList = [], params, manual } }) {
    this.setData({
      imgIdArr: idList
    })
  },

  /**
   * 图片删除
   * index: Number //删除的下表
   * params: params //自定义参数
   */
  imgUploadRemoveFun(e: any) {
    const { index, params } = e.detail || {};
    let imgIdArr = this.data.imgIdArr;
    imgIdArr.splice(index, 1);
    this.setData({
      imgIdArr
    })
  },

  /**
   * 提交验证
   */
  submit() {
    let {
      report, title, remarks, inputArticleLabels, inputArticleContent, imgIdArr,
      topicId, topicPlanId
    } = this.data;
    let formData = {
      ...report,
      articleName: title,// 标题
      articleLabels: inputArticleLabels,// 标签
      remarks,// 备注
      articleContent: inputArticleContent,// 备注
    }
    this.selectComponent("#form").validate(formData, rules).then(res => {
      if (formData.articleLabels.length === 0) {
        this.showToast('标签用于描述选题特点，至少填写一个');
        return
      }
      formData.articleAttachments = imgIdArr;
      formData.topicId = topicId;
      formData.topicPlanId = topicPlanId;
      this.saveFun(formData)
    }).catch(errors => {
      console.log(errors)
    })
  },

  /**
   * 保存函数
   */
  async saveFun(params) {
    wx.showLoading({
      title: "加载中..."
    })
    await saveCuesSubmit(params).then(async (res) => {
      if (res?.code === 0) {
        wx.hideLoading()
        handleCode(res, '新增成功');
        setTimeout(() => {
          wx.navigateBack({
            delta: 1
          })// 回到上一个界面
        }, 1000)
      } else {
        handleErrCode()
      }
    }).catch(e => {
      handleErrCode(e)
    })
  },

  /**
   * 显示提示
   */
  showToast(title) {
    let params = {
      title,
    }
    toast && toast.show(params);
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    toast = this.selectComponent("#toast")
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    wx.hideShareMenu({
      menus: ['shareAppMessage', 'shareTimeline'],// 隐藏分享到朋友和分享到朋友圈
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  taskExecuteShareFun() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
  }
})